<template>
    <table-header
        placeholder="请输入媒资名称"
        :queryList="queryList"
        @pagination="getDataList"
        :rightColSpan="8"
        :leftColSpan="16"
    >
        <template #filter>
            <!--<el-autocomplete
                v-model="queryList.keyword"
                :fetch-suggestions="handleSearchSuggest"
                :trigger-on-focus="false"
                class="inline-input"
                autofocus="true"
                :clearable="true"
                @clear="getDataList"
                placeholder="请输入媒资名称"
                @keyup.enter="getDataList"
                @select="getDataList"
                size="small"
            />-->
            <el-select
                v-model="queryList.mediatype"
                size="small"
                style="margin-right: 10px"
                placeholder="请选择媒资类型"
                @change="handleMediaTypeChange"
                clearable
                @clear="handleMediaTypeClear"
            >
                <el-option
                    v-for="item,index in mediaTypes"
                    :key="index"
                    :label="item"
                    :value="index"
                >
                </el-option>
            </el-select>
            <el-select
                v-model="queryList.catid"
                size="small"
                style="margin-right: 10px"
                placeholder="请选一级分类"
                @change="handleCategoryChange"
                clearable
                @clear="handleCategoryClear"
            >
                <el-option
                v-for="item in categoryData"
                :key="item.catid"
                :label="item.name"
                :value="item.catid">
                </el-option>
            </el-select>
            <el-input
                placeholder="请输入媒资名称"
                v-model="queryList.keyword"
                style="width: 200px"
                :clearable="true"
                @clear="handleKeywordClear"
                size="small"
                @keyup.enter="getDataList"
            />
        </template>
        <template #default>
            <el-button
                size="small"
                type="primary"
                style="margin-left: 10px"
                @click="getDataList"
            >
                搜索
            </el-button>
            <!--<el-button
                size="small"
                type="primary"
                @click="handleDialog('AndvancedSearch')"
            >
                高级搜索
            </el-button>-->
        </template>
        <template #operation>
            <el-dropdown @command="handleBatchCommand" style="margin-right:10px">
                <el-button size="small" type="primary">
                    批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="refpackage">批量加内容包</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </template>
    </table-header>
            <el-table
                class="mt10 mb10"
                v-loading="isloading"
                :data="tableData.listData"
                border
                :height="tableHeight"
                highlight-current-row
                @selection-change="handleSelectionChange"
                @row-click="(row) => {handleRowClick(row)}"
                @sort-change="handleTableSortChange"
                ref="tableref"
            >
                <el-table-column type="selection" width="40" />
                <el-table-column label="缩略图" width="60">
                    <template #default="{row}">
                        <span @click.stop>
                            <el-image
                                v-if="row.thumbs.length > 0 && typeof row.thumbs[0] == 'object'"
                                :preview-src-list="srcList"
                                :initial-index="srcList.indexOf(row.thumbs[0].viewurl)"
                                :src="(row.thumbs[0].isself == 1 && row.thumbs[0].sourcefrom == 'cloudstorage') ? row.thumbs[0].viewurl+'&width=50' : row.thumbs[0].viewurl"
                            />
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="媒资ID" prop="mediaid" width="80px" align="center" />
                <el-table-column label="媒资名称" :show-overflow-tooltip="true">
                    <template #default="{row}">
                        <a v-if="row.highlight && row.highlight.name" v-html="row.highlight.name" href="javascript:;" @click.stop="handleMediaDetail(row)"></a>
                        <a href="javascript:;" @click.stop="handleMediaDetail(row)" v-else>{{row.name}}</a>
                    </template>
                </el-table-column>
                <el-table-column label="媒资类型" width="70px" :show-overflow-tooltip="true" align="center">
                    <template #default="{row}">
                        {{row.mediatypename}}
                    </template>
                </el-table-column>
                <el-table-column label="媒资分类" width="70px" :show-overflow-tooltip="true" align="center">
                    <template #default="{row}">
                        <p>{{row.catname}}</p>
                    </template>
                </el-table-column>
                <el-table-column label="是否多集" width="70px" align="center">
                    <template #default="{row}">
                        <span v-if="row.hasseries == 1">是</span>
                        <span v-else>否</span>
                    </template>
                </el-table-column>
                <el-table-column label="来源企业" width="100px" align="center" :show-overflow-tooltip="true">
                    <template #default="{row}">
                        <span v-if="corpPartnerKeyValue[row.corpid] != undefined">{{corpPartnerKeyValue[row.corpid]}}</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" width="150px" align="center" prop="cts" sortable="custom">
                    <el-table-column label="更新时间" width="150px" align="center" prop="mts" sortable="custom">
                        <template #default="{row}">
                            {{row.ctime.replace('T', ' ').replace('Z', '')}}<br />
                            {{row.mtime.replace('T', ' ').replace('Z', '')}}
                        </template>
                    </el-table-column>
                </el-table-column>
                <!--<el-table-column label="关联内容包" :show-overflow-tooltip="true">
                    <template #default="{row}">
                        <template  v-if="row.packagenames && row.packagenames.length > 0">
                            <p class="txttdellipsis" v-for="packagename in row.packagenames" :key="packagename">{{packagename}}</p>
                        </template>
                        <template v-else>
                            -
                        </template>
                    </template>
                </el-table-column>-->
                <el-table-column label="审核状态" align="center">
                    <template #default="{row}">
                        <span v-if="row.state == 0">未提交</span>
                        <span v-else-if="row.state == 1">审核中</span>
                        <span v-else-if="row.state == 2">审核通过</span>
                        <span v-else-if="row.state == 3">审核失败</span>
                        <span v-else-if="row.state == 4">免审</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="付费类型" align="center">
                    <template #default="{row}">
                        <span v-if="row.paytype == 0" style="color:#67C23A">免费</span>
                        <span v-else-if="row.paytype == 1" style="color:#f56c6c">付费</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center">
                    <template #default="{row}">
                        <!--只有审核通过和免审时才可操作上下线-->
                        <el-button v-if="row.inuse == 1" type="text" size="mini" :disabled="true">上线</el-button>
                        <el-button v-else type="text" size="mini" :disabled="true">下线</el-button>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180px">
                    <template #default="{row}">
                        <el-button size="mini" type="text" @click.stop="handleDialog('RelPackage',row)">
                            加内容包
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <table-pagination
            :queryList="queryList"
            :total="tableData.total"
            @pagination="getDataList"
            />
    <component
        :is="asyncComponentAndvancedSearch"
        :title="dialogTitle"
        :visible="dialogVisible.AndvancedSearch"
        :queryList="queryList"
        @cancelDialog="cancelDialog('AndvancedSearch')"
        @getData="getDataList"
        @handleSearchSuggest="handleSearchSuggest"
    />
    <component
        :is="asyncComponentRelPackage"
        :title="dialogTitle"
        :visible="dialogVisible.RelPackage"
        :toDialogData="toDialogData"
        @getData="getDataList"
        @cancelDialog="cancelDialog('RelPackage')"
        :key="relPackageComponentsKey"
    />
</template>

<script>
    import { useRoute,useRouter } from 'vue-router';
    import {ref,reactive,defineAsyncComponent,onMounted} from 'vue';
    import TableHeader from "@/views/public/TableHeader";
    import TableData from "@/views/public/TableData";
    import TablePagination from "@/views/public/TablePagination";
    import {getSearchSuggest} from "@/api/media/media";
    import { getMediaShareList } from '@/api/corppartner/index'
    import {useStore} from 'vuex'
    import {Plus, ArrowDown} from "@element-plus/icons"
    import {ElMessage} from 'element-plus'
    import mediaTypeMixin from "@/mixins/mediaTypeMixin";
    import corpPartnerMixin from "@/mixins/corpPartnerMixin";
    import { getCategories } from '@/api/media/constant'
    export default {
        name: "medialist",
        components: {
            TableHeader,
            TableData,
            TablePagination,
            Plus,
            ArrowDown,
            "AndvancedSearch" : defineAsyncComponent(() => import('@/views/public/AndvancedSearch')),
            "RelPackage" : defineAsyncComponent(() => import('./components/RelPackageDialog')),
        },
        setup() {
            const relPackageComponentsKey = ref(Number)
            const store = useStore()
            const route = useRoute()
            const router = useRouter()
            const asyncComponentAndvancedSearch = ref(null)
            const asyncComponentRelPackage = ref(null)
            // 媒资类型
            const { mediaTypes } = mediaTypeMixin()
            const handleMediaTypeChange = () => {
                queryList.catid=''
                queryList.page = 1
                getCategory()
                getDataList()
            }
            const handleMediaTypeClear = () => {
                queryList.mediatype = ''
                queryList.catid = ''
                queryList.page = 1
                categoryData.value = []
                getDataList()
            }
            // 一级分类
            const categoryData = ref([])
            const getCategory = () => {
                categoryData.value = []
                if( queryList.mediatype != '' ){
                    getCategories({mediatype:queryList.mediatype,pagesize:1000}).then(response => {
                        if( response.errcode == 0 ){
                            categoryData.value = response.data.list
                        }else{
                            console.log(response)
                        }
                    })
                }
            }
            const handleCategoryChange = () => {
                queryList.page = 1
                getDataList()
            }
            const handleCategoryClear = () => {
                queryList.catid = ''
                queryList.page = 1
                getDataList()
            }
            const handleKeywordClear = () => {
                queryList.keyword = ''
                queryList.page = 1
                getDataList()
            }
            // 图片预览
            const srcList = ref([])
            // 搜索条件
            const queryList = reactive({
                'page': 1,
                'pagesize': 10,
                'keyword': '',
                'mediatype': '',
                'catid': '',
                'orderby': '',
                'type':2
            })
            // 接收参数
            const partnercorpid = route.query.partnercorpid
            if( partnercorpid != 0 ){
                queryList.partnercorpid = partnercorpid
            }
            // 列表相关
            const isloading = ref(true)
            const tableData = reactive({
                total: 0,
                listData: []
            })
            const getDataList = () => {
                isloading.value = true;
                //queryList.state=1
                getMediaShareList(queryList).then(response => {
                    isloading.value = false;
                    const {total, list} = response.data
                    tableData.total = total
                    tableData.listData = list
                    srcList.value = []
                    list.forEach(item => {
                        if( typeof item.thumbs[0] == 'object' ){
                            srcList.value.push(item.thumbs[0].viewurl)
                        }
                    })
                })
            }
            getDataList()
            // 搜索建议
            const handleSearchSuggest = (value,cb) =>{
                let suggestQuery = {}
                suggestQuery['corpid'] = store.getters.corpinfo.corpid
                suggestQuery['state'] = 1
                suggestQuery['prefix'] = value
                const suggestList = ref([])
                getSearchSuggest(suggestQuery).then(response => {
                    if( response.data.list.length > 0 ){
                        response.data.list.forEach(function( suginfo ){
                            suggestList.value.push({value:suginfo.name})
                        })
                        console.log(suggestList.value)
                    }
                })
                cb(suggestList.value)
            }
            // 弹窗相关
            const toDialogData = reactive({})
            const dialogTitle = ref('')
            const dialogVisible = ref({
                AndvancedSearch:false,
                RelPackage:false,
            })
            const handleDialog = ( dialogName, data ) => {
                toDialogData.value = {}
                switch ( dialogName ){
                    case 'AndvancedSearch':
                        dialogTitle.value = '高级搜索'
                        asyncComponentAndvancedSearch.value = 'AndvancedSearch'
                        break;
                    case 'RelPackage':
                        dialogTitle.value = '选择关联内容包'
                        asyncComponentRelPackage.value = 'RelPackage'
                        toDialogData.mediaids = [data.mediaid]
                        toDialogData.packageids = data.packageids
                        relPackageComponentsKey.value = new Date().getTime()
                        break;
                }
                dialogVisible.value[dialogName] = true
            }
            const cancelDialog = ( dialogName ) => {
                dialogVisible.value[dialogName] = false
            }
            // 媒资详情
            const handleMediaDetail = (row) => {
                router.push({path: '/fromcorpmedia/media/detail', query: {mediaid: row.mediaid, partnercorpid: route.query.partnercorpid, activename: 'mediagetlist', mediatype: row.mediatype}})
            }

            //复选框
            const batchCheckBoxData = ref([])
            const batchCheckBoxAllData = ref([])
            const tableHeight = ref()
            const tableref = ref(null)
            const handleSelectionChange = (val) => {
                batchCheckBoxData.value = []
                batchCheckBoxAllData.value = []
                if(val.length > 0){
                    val.forEach(function(item){
                        batchCheckBoxData.value.push(item.mediaid)
                        batchCheckBoxAllData.value.push(item)
                    })
                }
            }
            const handleRowClick = (row) => {
                tableref.value.toggleRowSelection(row)
            }
            //排序
            const handleTableSortChange = (column) => {
                if(column.order == 'ascending'){
                    queryList.orderby = column.prop
                }else if(column.order == 'descending'){
                    queryList.orderby = '-' + column.prop
                }else{
                    queryList.orderby = ''
                }
                getDataList()
            }
            // 批量操作
            const handleBatchCommand =(command) => {
                if( batchCheckBoxData.value.length == 0 ){
                    ElMessage({type: 'warning', message: '请选择批量操作的数据', duration: 2000})
                    return
                }
                //批量关联内容包特殊处理
                if(command == 'refpackage'){
                    dialogTitle.value = '选择批量关联内容包'
                    asyncComponentRelPackage.value = 'RelPackage'
                    toDialogData.mediaids = batchCheckBoxData.value
                    toDialogData.packageids = []
                    relPackageComponentsKey.value = new Date().getTime()
                    dialogVisible.value['RelPackage'] = true
                    return
                }
            }
            /* 获取互信企业---start */
            const { corpPartnerKeyValue } = corpPartnerMixin({partnertype:0})
            /* 获取互信企业---end */
            onMounted(() => {
                tableHeight.value =
                window.innerHeight - tableref.value.$el.offsetTop - 80;
            });

            return {
                relPackageComponentsKey,
                isloading,
                tableData,
                queryList,
                mediaTypes,
                handleMediaTypeChange,
                handleMediaTypeClear,
                categoryData,
                handleCategoryChange,
                handleCategoryClear,
                handleKeywordClear,
                srcList,
                getDataList,
                handleSearchSuggest,
                handleMediaDetail,
                asyncComponentAndvancedSearch,
                asyncComponentRelPackage,
                toDialogData,
                dialogTitle,
                dialogVisible,
                handleDialog,
                cancelDialog,
                handleSelectionChange,
                handleRowClick,
                handleTableSortChange,
                tableref,
                handleBatchCommand,
                corpPartnerKeyValue,
                tableHeight
            }
        }
    }
</script>

<style scoped  lang="scss">

</style>
